window.onload = function () {
  let token = localStorage.getItem("token");
  if (token != null) {
    //如果token没有，则会显示还未登录

    login(undefined, token);
  } else {
    alert("您還未登錄呢？");
    window.location.href = "/login.html";
  }
  //删除
  document.querySelector(".tbody").addEventListener("click", (e) => {
    if (e.target.innerHTML == "删除") {
      del(e.target.id, token);
    }
  });
};

let del = async (del_id, token) => {
  let data = null;
  try {
    data = await ajax_post_del(del_id, token);
  } catch (error) {
    alert(error);
    window.location.href = "login.html";
  }

  data != null ? xuan(data.result) : "";
};

let login = async (data, token) => {
  let res = null;
  try {
    res = await ajax_post(data, token);
  } catch (error) {
    alert(error);
    window.location.href = "login.html";
  }
  if (res != null) {
    xuan(res.obj);
  }
};

function xuan(arr) {
  let str = arr
    .map((v) => {
      let row = `
       <tr>
       <td>${v.sid}</td>
       <td>${v.sname}</td>
       <td>${v.gender == 1 ? "男" : "女"}</td>
       <td>${v.telephone}</td>
       <td>${v.classId.className}</td> 
       <td>${v.classId.teacher}</td> 
       <td>${v.classId.people_num}</td>
       <td id=${v.sid}>删除</td>
       </tr>
       `;
      return row;
    })
    .join("");
  document.querySelector(".tbody").innerHTML = str;
}

function ajax_post(data, token) {
  return new Promise((res, rej) => {
    let xhr = new XMLHttpRequest();
    xhr.open("get", "http://172.16.8.193:4000/students/GetAllStudents_class");
    if (token) {
      xhr.setRequestHeader("Authorization", token);
    }

    xhr.send();

    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          res(JSON.parse(xhr.responseText));
        } else if (xhr.status == 401) {
          rej("页面需要重新登录");
        }
      }
    };
  });
}

function ajax_post_del(del_id, token) {
  return new Promise((res, rej) => {
    let xhr = new XMLHttpRequest();
    xhr.open("post", "http://172.16.8.193:4000/students/deleteStudents");
    if (token) {
      xhr.setRequestHeader("Authorization", token);
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(`sid=${del_id}`);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          res(JSON.parse(xhr.responseText));
        } else if (xhr.status == 401) {
          rej("页面需要重新登录");
        }
      }
    };
  });
}
